package com.zjsru.plan2023.oneday.oneDay202301;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: CookLee
 * @Date: 2023/1/8
 * 统计包含给定前缀的字符串
 *
 * 输入：words = ["pay","attention","practice","attend"], pref = "at"
 * 输出：2
 * 解释：以 "at" 作为前缀的字符串有两个，分别是："attention" 和 "attend" 。
 */
public class PrefixCount {
    
    public int prefixCount(String[] words, String pref) {
        int prefLength = pref.length();
        int count = 0;
        //过滤出比pref小的字符串，防止越界
        List<String> list = Arrays.stream(words).filter(v -> v.length() >= pref.length()).collect(Collectors.toList());
        for (String s : list) {
            if (s.substring(0, prefLength).equals(pref)) {
                count++;
            }
        }
        return count;
    }
    
    /***
     * 使用api的方式
     * */
    public int prefixCount2(String[] words, String pref) {
        int res = 0;
        for (String word : words) {
            if (word.startsWith(pref)) {
                res++;
            }
        }
        return res;
    }
    
    public static void main(String[] args) {
        PrefixCount prefixCount = new PrefixCount();
        String[] words = new String[] {"pay", "attention", "practice", "attend"};
        String pref = "at";
        System.out.println(prefixCount.prefixCount(words, pref));
    }
}
